/**
 * 
 */
package com.jintian.smart.kernel.common.expr.format.reader;

import com.jintian.smart.kernel.common.expr.format.Element;
import com.jintian.smart.kernel.common.expr.format.ExpressionReader;
import com.jintian.smart.kernel.common.expr.format.FormatException;
import com.jintian.smart.kernel.common.expr.op.Operator;

import java.io.IOException;

/**
 * 读取运算符类型
 */
public class OperatorTypeReader implements ElementReader {

	/**
	 * 从流中读取运算符类型的ExpressionToken
	 * 
	 * @param sr
	 * @return
	 * @throws FormatException
	 *             不是合法的运算符类型时抛出
	 * @throws IOException
	 */
	public Element read(ExpressionReader sr) throws FormatException, IOException {
		int index = sr.getCruuentIndex();
		StringBuffer sb = new StringBuffer();
		int b = sr.read();
		if (b == -1) {
			throw new FormatException("表达式已结束");
		}
		char c = (char) b;
		sb.append(c);
		if (Operator.isOperatorWord(sb.toString())) {
			if (sb.length() == 1) {// 两个符号的运算符优先，如<=，不应该认为是<运算符
				sr.mark(0);
				b = sr.read();
				if (b != -1) {
					if (Operator.isOperatorWord(sb.toString() + (char) b)) {
						return new Element(sb.toString() + (char) b, index, Element.ElementType.OPERATOR);
					}
				}
				sr.reset();
			}
			return new Element(sb.toString(), index, Element.ElementType.OPERATOR);
		}

		while ((b = sr.read()) != -1) {
			c = (char) b;
			sb.append(c);
			if (Operator.isOperatorWord(sb.toString())) {
				return new Element(sb.toString(), index, Element.ElementType.OPERATOR);
			}
			if (VariableTypeReader.STOP_CHAR.indexOf(c) >= 0) {// 单词停止符
				throw new FormatException("不是有效的运算符：" + sb.toString());
			}
		}
		throw new FormatException("不是有效的运算符结束");
	}

	/**
	 * 测试是否为运算符
	 * 
	 * @param sr
	 * @return
	 * @throws IOException
	 */
	public static boolean isOperatorStart(ExpressionReader sr) throws IOException {
		sr.mark(0);
		try {
			StringBuffer sb = new StringBuffer();
			int b = sr.read();
			if (b == -1) {
				return false;
			}
			char c = (char) b;
			sb.append(c);
			if (Operator.isOperatorWord(sb.toString())) {
				return true;
			}
			while ((b = sr.read()) != -1) {
				c = (char) b;
				sb.append(c);
				if (Operator.isOperatorWord(sb.toString())) {
					return true;
				}
				if (VariableTypeReader.STOP_CHAR.indexOf(c) >= 0) {// 单词停止符
					return false;
				}

			}
			return false;
		} finally {
			sr.reset();
		}

	}
}
